'use strict';
const {
  validateBody,
  validateQuery,
  validateParams,
  presence,
  isInt,
} = require('property-validator');
const RecomeData = require('@utils/recomeData');
const { ParameterException } = require('@utils/http-exception');

function validateHouseId(name) {
  return function(sub) {
    let message = 'ok';
    let result = true;
    if (sub[name] === 'undefined' || sub[name] == null) {
      message = 'houseId不能为空';
      result = false;
    }
    return {
      result,
      message,
      field: name,
    };
  };
}

async function addCommentValidate(ctx) {
  const { valid, errors } = validateBody(ctx.request, [
    presence('comment', 'comment不能为空'),
  ]);
  const { valid: valid2, errors: err2 } = validateParams(ctx, [
    validateHouseId('houseId'),
  ]);
  if (!valid) {
    throw new ParameterException(errors);
  }
  if (!valid2) {
    throw new ParameterException(err2);
  }

  const v = new RecomeData(ctx);
  return v;
}

async function commentListValidate(ctx) {
  const { valid: valid1, errors: err1 } = validateQuery(ctx, [
    isInt('pageNum', 'pageNum不能为空'),
    isInt('pageSize', 'pageSize不能为空'),
  ]);

  const { valid: valid2, errors: err2 } = validateParams(ctx, [
    validateHouseId('houseId'),
  ]);

  if (!valid1) {
    throw new ParameterException(err1);
  }
  if (!valid2) {
    throw new ParameterException(err2);
  }

  const v = new RecomeData(ctx);
  return v;
}

module.exports = {
  addCommentValidate,
  commentListValidate,
};
